package com.xidian.zhiancloud.service.workTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.workTicket.ElectricFlowMapper;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.workTicket.ElectricFlow;
import com.xidian.zhiancloud.model.workTicket.ElectricTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ElectricFlowService extends ServiceImpl<ElectricFlowMapper, ElectricFlow> implements IService<ElectricFlow> {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ElectricFlowMapper electricFlowMapper;

    /**
     *
     *
     * @param currentStep 当前所在步骤
     * @param electricTicket  当前作业票已实现内容
     * @return
     */
    public Integer updateCurrentStep(Integer currentStep, ElectricTicket electricTicket) {
        Boolean isFinishCurrentStep = false;        // 假设大步骤未完成
        switch (currentStep) {
            case 1:
                if (electricTicket.getIsCommit1() != null && electricTicket.getIsCommit1() == 1) isFinishCurrentStep = true; break;
            case 2:
                if (electricTicket.getIsCommit2() != null && electricTicket.getIsCommit2() == 1) {
                    //所有作业人都提交完毕
                    String[] split = electricTicket.getOperatorIds().split(",");
                    if (split.length == electricTicket.getOperatorNumber()){
                        isFinishCurrentStep = true;
                    }
                    break;
                }
            case 3:
                if ((electricTicket.getIsCommit3() == 1) && (electricTicket.getIsCommit4() == 1) && (electricTicket.getIsCommit5() == 1)) isFinishCurrentStep = true; break;
            case 4:
                if (electricTicket.getIsCommit6() == 1) isFinishCurrentStep = true; break;
            case 5:
                if (electricTicket.getIsCommit7() == 1) isFinishCurrentStep = true; break;
            case 6:
                if (electricTicket.getIsCommit8() == 1) isFinishCurrentStep = true; break;
            case 7:
                if (electricTicket.getIsCommit9() == 1) isFinishCurrentStep = true; break;
            case 8:
                if (electricTicket.getIsCommit10() == 1) isFinishCurrentStep = true; break;
            case 9:
                if ((electricTicket.getIsCommit11() == 1) && (electricTicket.getIsCommit12() == 1)) isFinishCurrentStep = true; break;
        }
        // isFinishCurrentStep为true，则完成该大步
        return isFinishCurrentStep ? currentStep + 1 : currentStep;
    }


    /**
     * 根据筛选条件获取对应流程的可编辑人员列表
     *
     * @param selectStandard
     * @param ids_s
     * @param companyId
     * @return
     */
    List<Long> getPeopleIds(Integer selectStandard, String ids_s, Long companyId) {
        String[] ids = ids_s.split(",");
        Map<String, Boolean> isIdExist = new HashMap<>();
        for (String id : ids) {
            isIdExist.put(id, Boolean.TRUE);
        }
        //
        LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
        query.eq(SysUser::getCompanyid, companyId);
        List<SysUser> sysUsers = sysUserMapper.selectList(query);

        List<Long> user_ids = new LinkedList<>();

        // 根据职位选择
        if (selectStandard == 0) {
            sysUsers.forEach(user -> {
                String jobIdStr = user.getJobids();
                if (jobIdStr == null) {
                    return;
                }
                String[] jobIds = jobIdStr.split(",");
                for (String jobId : jobIds) {
                    if (isIdExist.get(jobId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

/*        // 根据角色选择
        else if (selectStandard == 1) {
            sysUsers.forEach(user -> {
                String roleIdStr = user.getRoleids();
                if (roleIdStr == null) {
                    return;
                }
                String[] roleIds = roleIdStr.split(",");
                for (String roleId : roleIds) {
                    if (isIdExist.get(roleId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

        // 根据岗位选择
        else if (selectStandard == 2) {
            sysUsers.forEach(user -> {
                String depIdStr = user.getDepartids();
                if (depIdStr == null) {
                    return;
                }
                String[] departIds = depIdStr.split(",");
                for (String departId : departIds) {
                    if (isIdExist.get(departId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });

        }*/

/*        // 根据组织机构选择
        else if (selectStandard == 3) {
            sysUsers.forEach(user -> {
                String orgIdStr = user.getOrgids();
                if (orgIdStr == null) {
                    return;
                }
                String[] orgIds = orgIdStr.split(",");
                for (String orgId : orgIds) {
                    if (isIdExist.get(orgId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }*/

        // 根据人员id选择
        else if (selectStandard == 1) {
            sysUsers.forEach(user -> {
                Long userId = user.getId();
                if (isIdExist.get(userId) != null) {
                    user_ids.add(user.getId());
                }
            });
        }

        return user_ids;
    }

    /**
     * 根据当前步骤id返回可编辑字段list
     *
     * @param flowId
     * @return
     */
    public List<String> getEnableFieldList(Long flowId) {
        ElectricFlow electricFlow = getById(flowId);
        String enableFieldStr = electricFlow.getEnableField();
        List<String> enableFields = new LinkedList<>();
        for (String enableField : enableFieldStr.split(",")) {
            enableFields.add(enableField);
        }
        return enableFields;
    }

    /**
     * 根据当前步骤id返回具有操作权限人员的id的List
     *
     * @param flowId
     * @return
     */
    public List<Long> getOperatorIdsList(Long flowId, Long companyId) {
        // 根据id获取当前步骤的内容
        ElectricFlow electricFlow = getById(flowId);
        // 获取人员筛选的ids
        String ids_s = electricFlow.getSelectPerson();
        // 通过选择标准进行筛选
        Integer selectStandard = electricFlow.getSelectStandard();
        List<Long> operatorIds = getPeopleIds(selectStandard, ids_s, companyId);
        return operatorIds;
    }

    /**
     * 根据大步骤currentStep的id在t_electric_flow中获取相关小步骤id的List
     *
     * @param currentStep
     * @return
     */
    public List<Long> getSubIdsByCurrent(Long companyId, Integer currentStep) {
        List<Long> subIdList = new LinkedList<>();
        LambdaQueryWrapper<ElectricFlow> query = Wrappers.<ElectricFlow>lambdaQuery();
        query.eq(ElectricFlow::getBelongId, currentStep).eq(ElectricFlow::getCompanyId, companyId);
        List<ElectricFlow> electricFlows = list(query);
        electricFlows.forEach(subId -> {
                subIdList.add(subId.getId());
            }
        );
        return subIdList;
    }


    /**
     * 根据electricTicket的isCommit**字段判断哪一个小步骤完成提交。
     *
     * @param electricTicket
     * @return
     */
    public Integer getFinishSubId(Integer currentStep, ElectricTicket electricTicket) {
        Integer subStep = 0;                                                // 初始化subStep
        if (currentStep == 1)  subStep = 1;                                 // 当前在第一大步骤，则必在第1小步骤
        else if (currentStep == 2) subStep = 2;
        else if (currentStep == 3) {
            if (electricTicket.getOperationSign() != null) subStep = 3;
            if (electricTicket.getBelongPlaceSign() != null) subStep = 4;
            if (electricTicket.getPowerTransmissionSign() != null) subStep = 5;
        }
        else if (currentStep == 4) subStep = 6;
        else if (currentStep == 5) subStep = 7;
        else if (currentStep == 6) subStep = 8;
        else if (currentStep == 7) subStep = 9;
        else if (currentStep == 8) subStep = 10;
        else if (currentStep == 9) {
            if (electricTicket.getWorkManagerAcceptanceSign() != null) subStep = 11;
            if (electricTicket.getElectricLeaderSign() != null) subStep = 12;
        }
        return subStep;
    }

    public Boolean signOvertime(Date applyTime, Date nowTime) {
        // getTime()方法返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数
        long startTime = applyTime.getTime();
        long endTime = nowTime.getTime();
        // 时间间隔，单位为小时
        long timeInterval = endTime - startTime;
        double result = timeInterval / (1000 * 60 * 60 * 24 * 30); // 30天超时

        return result > 1.0;
    }

    /**
     * 根据subId，查找对应的t_electric_ticker的id
     *
     * @param companyId
     * @param subId
     * @return
     */
    public Long getFlowBySubId(Long companyId, Integer subId) {
        Long flowId = null;
        // 根据companyId查询fireFlow
        LambdaQueryWrapper<ElectricFlow> query = Wrappers.<ElectricFlow>lambdaQuery();
        query.eq(ElectricFlow::getCompanyId, companyId);
        List<ElectricFlow> electricFlows = list(query);

        // 在初次筛选的fireFlow中，根据subId获取id
        for (int i = 0; i < electricFlows.size(); i++) {
            if (electricFlows.get(i).getSubId() == subId) {
                flowId = electricFlows.get(i).getId();
                break;
            }
        }

        return flowId;
    }

}
